<template>
  <el-upload
    class="avatar-uploader"
    action="upload/api/v1/files/upload"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    :data="additionalParameters"
    name="uploadFile"
    :headers="{ Authorization: token }"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>
<script>
export default {
  data() {
    return {
      imageUrl: "",
      token:
        "eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWyirJVLJSSk1NtDBONEvRNU8yT9Y1MTNO1LVISU7WTbM0T0sxNUwzNrVIVtJRykwsUbIyNDcwNbawMDIz01FKrSiAClgaWoAEkvNznVJz8vPSPVOAEmamSCJAa57sWPti_axnM3c92b_w6ey1T3t2Pe1oe9q65mn_DqDpBfnFQOOVXuxd_2T3tqfblz5f0f10RwdQIi8xNxUo8XJmx7M504H83PykzByQiKGlqZG5uYWhkbEhyHUgKw2NzHWUUlILEotKclPzQOY9XzDlaf_El80rlGoB8H3IkO8AAAA.RgECG9UMImplgArNFrjoT0cE56U5NUnd0ODcHrA18cEgdj2fN4HCi1ldyaC2Hi1MNAMiDDzzbYEI-YYloBUd0A",
      additionalParameters: {
        name: "",
        ext: "",
        size: "",
        md5: "",
      },
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.$emit("sent-uploaded-res", res);
      this.$emit("preview-url", this.imageUrl);
      this.$message.success("上传成功！");
    },
    beforeAvatarUpload(file) {
      this.additionalParameters.name = file.name;
      this.additionalParameters.ext = this.getFileExtension(file.name);
      this.additionalParameters.size = file.size;
      this.additionalParameters.md5 = file.uid;
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    getFileExtension(fileName) {
      const lastDotIndex = fileName.lastIndexOf(".");
      if (lastDotIndex !== -1 && lastDotIndex < fileName.length - 1) {
        return fileName.slice(lastDotIndex + 1);
      } else {
        return "unKnow"; // 文件名中没有后缀
      }
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
